<template>
    <div>
        <div class="form">
            <el-form :inline="true" class="demo-form-inline">
                <el-form-item>
                    <el-input v-model="username" placeholder="请输入管理员名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div>
            <el-table :data="tableData" style="width: 100%" border>
                <el-table-column label="管理员ID" prop="id" />
                <el-table-column label="管理员名称" prop="username" />
                <el-table-column label="真实姓名" prop="realname" />
                <el-table-column label="电话" prop="phone" />
                <el-table-column label="管理员角色">
                    <template #default="scope">
                        <div class="roleid" v-for="item in roleIds" :key="item.id">
                            <div class="roleid" v-for="items in scope.row.roleIds" :key="items">
                                <el-tag v-if="item.id == items">{{ item.name }}</el-tag>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div>
            <Pagetion v-bind="pagetio" @page-change="pageChange"></Pagetion>
        </div>
        <div>
            <el-backtop target=".el-main" :right="100" :bottom="100" ref="backTop" :visibility-height="20" />
        </div>
        <div>
            <el-dialog v-model="dialogFormVisible" :title="title" :destroy-on-close="true">
                <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px"
                    class="demo-ruleForm">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="ruleForm.username" autocomplete="off" clearable :disabled="title == '编辑'" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password" v-if="title == '创建'">
                        <el-input v-model="ruleForm.password" type="password" autocomplete="off" clearable />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model.number="ruleForm.phone" clearable />
                    </el-form-item>
                    <el-form-item label="真实姓名" prop="realname">
                        <el-input v-model.number="ruleForm.realname" clearable />
                    </el-form-item>
                    <el-form-item label="角色" :prop="title == '编辑' ? 'roleIds' : ''">
                        <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择角色" style="width: 240px">
                            <el-option v-for="item in roleIds" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button type="primary" @click="submitForm(ruleFormRef)">
                            {{ title == "创建" ? '新增' : '修改' }}
                        </el-button>
                        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, nextTick } from "vue";
import { Search, Plus } from '@element-plus/icons-vue'
import { ClassPagination } from "#/index";
import { post } from "@/http/request";
import { ElMessage, ElMessageBox } from "element-plus";
import Pagetion from "@/components/pagetion/Pagetion.vue";
import type { FormInstance } from 'element-plus'

const backTop = ref()//回到顶部
const username = ref("")//搜索 用户名称
const pagetio = reactive(new ClassPagination())
const tableData = ref<TypeAdmin[]>([])//接收表格数据
const roleIds = ref<TypeRole[]>([])//接收角色数据
const title = ref("")//弹窗title
const dialogFormVisible = ref(false)//弹窗是否显示
const ruleFormRef = ref<FormInstance>()

// 初始化数据传递的参数
let params = reactive({
    _gp: "admin",
    _mt: "list",
    username: "",
    page: pagetio.pageNo,
    limit: pagetio.pageSize
})

// 添加编辑传递的参数
const ruleForm = reactive({
    id: 0,
    username: '',
    password: '',
    phone: '',
    realname: '',
    roleIds: []
})
const form = reactive({ ...ruleForm })

// 密码验证
const validatePass = (rule: Object, value: string, callback: Function) => {
    if (value.length < 6) {
        callback(new Error("密码长度不能小于6位数！"))
    } else {
        callback()
    }
}
// 手机号验证
const validatePhone = (rule: Object, value: string, callback: Function) => {
    let reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/; //11位手机号码正则
    if (!reg_tel.test(value)) {
        callback(new Error("请正确填写您的手机号码！"))
    } else {
        callback()
    }
}
// 真实姓名验证
const validateRealname = (rule: Object, value: string, callback: Function) => {
    let reg_Realname = /^[\u4e00-\u9fa5]{1,}$/;//中文字符正则
    if (!reg_Realname.test(value)) {
        callback(new Error("请输入中文真实姓名！"))
    } else {
        callback()
    }
}

// 验证规则
const rules = reactive({
    //用户名
    username: [{ required: true, message: '请输入用户名', trigger: 'blur' },],
    //密码
    password: [
        { validator: validatePass, trigger: 'blur' },
        { required: true, message: '请输入密码', trigger: 'blur' },

    ],
    // 手机号
    phone: [
        { validator: validatePhone, trigger: 'blur' },
        { required: true, message: '请输入手机号', trigger: 'blur' },
    ],
    // 真实姓名
    realname: [
        { validator: validateRealname, trigger: 'blur' },
        { required: true, message: '请输入真实姓名', trigger: 'blur' },
    ],
    // 角色
    roleIds: [{ required: true, message: '请选择角色', trigger: 'change' },]
})

// 初始化数据
function loadInit() {
    post(params).then(res => {
        console.log(res);
        let { data, errno, errmsg } = res
        if (200 == errno) {
            tableData.value = data.items
            pagetio.total = data.total
        } else {
            return ElMessage.error(errmsg)
        }
    }).then(() => {
        let paramsRole = reactive({
            _gp: "admin.role",
            _mt: "list",
        })
        if (roleIds.value.length == 0) {
            post(paramsRole).then(res => {
                roleIds.value = res.data.items
            })
        }
    })
}
loadInit()

// 搜索
function handleSearch() {
    params.username = username.value
    loadInit()
}

// 添加
function handleAdd() {
    Object.assign(ruleForm, form)
    dialogFormVisible.value = true
    title.value = "创建"
}

// 修改
function handleEdit(row: TypeAdmin) {
    Object.assign(ruleForm, row)
    title.value = "编辑"
    dialogFormVisible.value = true
}

// 添加编辑请求
function submitForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            let parameter = {
                _gp: "admin",
                _mt: ruleForm.id ? "edit" : "create",
                adminDTO: JSON.stringify({ ...ruleForm })
            }
            post(parameter).then(res => {
                console.log(res);
                let { errno, errmsg } = res
                if (200 == errno) {
                    ElMessage.success("添加成功")
                    dialogFormVisible.value = false
                    loadInit()
                } else {
                    ElMessage.error(errmsg)
                }
            })
        } else {
            return false
        }
    })
}

// 重置
function resetForm(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.resetFields()
}

// 删除
const handleDelete = (row: TypeAdmin) => {
    let delParams = reactive({
        _gp: "admin",
        _mt: "delete",
        id: row.id
    })

    ElMessageBox.confirm(
        '是否删除该管理员？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        post(delParams).then(res => {
            let { errno, errmsg } = res
            if (200 == errno) {
                ElMessage.success("删除成功")
                loadInit()
            } else {
                ElMessage.error(errmsg)
            }
        })
    })
}

// 分页组件子传父自定义事件
const pageChange = (e: TypePage) => {
    params.page = e._pageNo
    params.limit = e._pageSize
    loadInit()
    nextTick(() => {
        backTop.value.$el.click?.()
    })
}
</script>

<style lang="less" scoped>
.el-input {
    width: 300px;
}

.el-form-item {
    margin-right: 15px !important;
}

.roleid {
    display: inline-block;
}

.el-tag {
    margin: 1px;
}

.el-dialog__body {
    .el-form-item {
        margin-bottom: 20px !important;
    }

    .el-input {
        width: 500px !important;
    }
}
</style>